/**
 * 复制文本到剪贴板
 *
 * @param {Boolean} onceEnabled 是否只执行一次
 * @returns {Function}
 */
export function useClipboardCopy(onceEnabled = true) {
  let called = false;

  return function (event, callback) {
    if (onceEnabled && called) {
      return;
    }
    called = true;
    let text = event;
    if (Object.prototype.toString.call(event) === '[object PointerEvent]') {
      text = event.target.innerText;
    }

    if (text && navigator.clipboard) {
      navigator.clipboard
        .writeText(text)
        .then(callback)
        .catch((error) => Promise.reject(error));
    } else {
      return new Promise.reject(new TypeError('navigator.clipboard is not defined'));
    }
  };
}
